package vn.com.hung.notetaker.utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import vn.com.hung.notetaker.datatypes.BookRecord;
import vn.com.hung.notetaker.datatypes.BookTags;

public class BookDataLoader extends AbstractLoader{
    
    
    private List<BookRecord> books = new ArrayList<BookRecord>();
    
    public BookDataLoader() { }
    
    public BookDataLoader(String filePath) {
        super(filePath);
    }
    
    public void load() {
        try {
            File bookData = new File(path);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(bookData);
            doc.getDocumentElement().normalize();
            
            NodeList bookList = doc.getElementsByTagName(BookTags.BOOK_TAG);
            
            for (int i = 0; i < bookList.getLength(); i++) {
                Node node = bookList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element elem = (Element) node;
                    BookRecord book = new BookRecord();
                    book.setName(getValue(BookTags.TITLE_TAG, elem));
                    book.setAuthor(getValue(BookTags.AUTHOR_TAG, elem));
                    book.setStatus(getValue(BookTags.STATUS_TAG, elem));
                    books.add(book);
                }
            }
        } catch (Exception e) {
            DialogDisplayer.showDefaultErrorDialog("input is not valid");
        }
        

    }
    
    public List<BookRecord> getBookList() {
        return books;
    }
    
    private String getValue(String tag, Element elem) {
        NodeList nodes = elem.getElementsByTagName(tag).item(0).getChildNodes();
        Node node = (Node) nodes.item(0);
        return node.getNodeValue();
    }
      
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        BookDataLoader loader = new BookDataLoader();
        loader.setPath("/home/hung/Desktop/data.xml");
        loader.load();
        
    }

}
